﻿<%@ WebHandler Language="C#" Class="RbSkillTargetMaint" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;

/**
 * Description: 热表厂技能指标维护功能
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2025.6.18
 **/

public class RbSkillTargetMaint : IHttpHandler
{
    public bool IsReusable { get { return false; } }
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    TreeObject t = new TreeObject();
    List<TreeObject> treeNodes = new List<TreeObject>();
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "isAlreadyExists":
                        r = isAlreadyExists(jObject);//校验是否存在
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "addSkillTarget":
                        r = addSkillTarget(jObject);//添加指标
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "updateStatus":
                        r = updateStatus(jObject);//更新启用状态
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "updateSkillTarget":
                        r = updateSkillTarget(jObject);//更新指标信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "deleteSkillTarget":
                        r = deleteSkillTarget(jObject);//删除指标
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询数据
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT sk.id,sk.skilltargetname,f.factoryname || '/' || wc.workcentername || '/' || te.teamname orginfo,
       sk.notes,NVL(sk.isuse,'0') isuse,
       e.fullname createemp,sk.createdate,e2.fullname lastchangeemp,sk.lastchangedate,
       f.factoryid,wc.workcenterid,sk.teamid,sk.skilltype
FROM rbskilltargetmaint sk
LEFT JOIN employee e ON e.employeeid = sk.createemployee
LEFT JOIN employee e2 ON e2.employeeid = sk.lastchangeemployee
INNER JOIN team te ON te.teamid = sk.teamid
LEFT JOIN workcenter wc ON wc.workcenterid = te.workcenterid
LEFT JOIN factory f ON f.factoryid = wc.factoryid
WHERE 1=1
";
        //指标名称
        if (jObject["skilltargetname"] != null && jObject["skilltargetname"].ToString() != "")
        {
            sql += string.Format(" AND sk.skilltargetname LIKE '%{0}%'", jObject["skilltargetname"].ToString());
        }

        //指标类型
        if (jObject["skilltype"] != null && jObject["skilltype"].ToString() != "")
        {
            sql += string.Format(" AND sk.skilltype = '{0}'", jObject["skilltype"].ToString());
        }

        //组织架构
        if (jObject["selectOrg"] != null && jObject["selectOrg"].ToString() != "")
        {
            JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
            if (selectOrg.Count == 3)
            {
                sql += string.Format(" AND te.teamid = '{0}'", selectOrg[2].ToString());
            }
            if (selectOrg.Count == 2)
            {
                sql += string.Format(" AND wc.workcenterid = '{0}'", selectOrg[1].ToString());
            }
            if (selectOrg.Count == 1)
            {
                sql += string.Format(" AND f.factoryid = '{0}'", selectOrg[0].ToString());
            }
        }

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //校验指标是否已经存在
    Result isAlreadyExists(JObject obj)
    {
        string sql = @"SELECT * FROM rbskilltargetmaint sk WHERE sk.teamid = '{0}' AND sk.skilltargetname = '{1}'";
        JArray selectOrg = JArray.Parse(obj["selectOrg"].ToString());
        string teamid = selectOrg[2].ToString();
        sql = string.Format(sql, teamid, obj["skilltargetname"].ToString());

        if (obj["id"] != null && obj["id"].ToString() != "")
        {
            sql += string.Format(" AND sk.id <> '{0}'", obj["id"].ToString());
        }

        DataTable dt = dal.GetDataTable(sql);
        Result r = new Result();
        r.data = dt.Rows.Count > 0;
        r.total = dt.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //添加指标
    Result addSkillTarget(JObject jObject)
    {
        string sql = @"
INSERT INTO rbskilltargetmaint(id,skilltargetname,teamid,createemployee,createdate,isuse,notes,skilltype)
VALUES('{0}','{1}','{2}','{3}',sysdate,'{4}','{5}','{6}')";

        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        string id = Guid.NewGuid().ToString();
        string skilltargetname = jObject["skilltargetname"] != null ? jObject["skilltargetname"].ToString() : "";//指标名称
        string teamid = selectOrg[2].ToString();
        string createemployee = jObject["employeeid"].ToString();
        string isuse = "0";
        string notes = jObject["notes"].ToString();
        string skilltype = jObject["skilltype"].ToString();
        sql = string.Format(sql, id, skilltargetname, teamid, createemployee, isuse, notes, skilltype);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //更新指标
    Result updateSkillTarget(JObject jObject)
    {
        string sql = @" 
UPDATE rbskilltargetmaint t 
SET t.skilltargetname='{1}',t.teamid = '{2}',t.notes='{3}',t.lastchangeemployee = '{4}',t.skilltype = '{5}',t.lastchangedate = sysdate 
WHERE t.id='{0}' ";

        string id = jObject["id"].ToString();
        string skilltargetname = jObject["skilltargetname"].ToString();
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        string teamid = selectOrg[2].ToString();
        string notes = jObject["notes"].ToString();
        string lastchangeemployee = jObject["employeeid"].ToString();
        string skilltype = jObject["skilltype"].ToString();

        sql = string.Format(sql, id, skilltargetname, teamid, notes, lastchangeemployee, skilltype);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //更新启用状态
    Result updateStatus(JObject jObject)
    {
        string sql = @"UPDATE rbskilltargetmaint t SET t.isuse='{1}',t.lastchangeemployee = '{2}',t.lastchangedate = sysdate WHERE t.id='{0}' ";
        string isuse = "";
        if (jObject["isuse"] != null)
        {
            isuse = jObject["isuse"].ToString() == "True" ? "0" : "1";
        }

        string employeeid = "";
        if (jObject["employeeid"] != null)
        {
            employeeid = jObject["employeeid"].ToString();
        }

        sql = string.Format(sql, jObject["id"].ToString(), isuse, employeeid);
        int count = dal.ExecuteSql(sql);

        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //删除指标
    Result deleteSkillTarget(JObject jObject)
    {
        string sql = string.Format("DELETE rbskilltargetmaint t where t.id = '{0}'", jObject["id"].ToString());
        int count = dal.ExecuteSql(sql);
        //删除完技能指标后，一并删除技能矩阵
        if (count > 0)
        {
            dal.ExecuteSql(string.Format("DELETE rbskilltargetemp rt WHERE rt.rbskilltargetmaintid = '{0}'", jObject["id"].ToString()));
        }
        Result r = new Result();
        r.data = null;
        r.total = count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}